/*
 * @description: vite配置
 * @Author: Islands
 * @Date: 2023-05-31 10:52:20
 * @LastEditTime: 2024-03-26 22:22:54
 */
import { loadEnv, defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import Unocss from 'unocss/vite'
import { resolve } from 'path';
import AutoImport from "unplugin-auto-import/vite";
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import ElementPlus from 'unplugin-element-plus/vite'

// https://vitejs.dev/config/
export default defineConfig(async ({ command, mode }) => {
  //获取本地文件;process会报错，需要安装 npm i --save-dev @types/node
  const env = loadEnv(mode, process.cwd(), '');
  return {
    plugins: [
      Unocss(),
      vue(),
      //配置自动导入element start
      AutoImport({
        resolvers: [
          ElementPlusResolver({
            // 自动引入修改主题色添加这一行，使用预处理样式，不添加将会导致使用ElMessage，ElNotification等组件时默认的主题色会覆盖自定义的主题色
            importStyle: "sass",
          }),
        ],
      }),
      //按需引入element-plus图标
      // ElementPlus({
      //   useIcons: true,
      // }),
      Components({
        extensions: ['vue', 'md'],
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
        dts: 'src/components.d.ts',
        resolvers: [
          ElementPlusResolver({
            // 自动引入修改主题色添加这一行，使用预处理样式
            importStyle: 'sass',
          }),
        ],

      }),
    ],
    //别名配置
    resolve: {
      alias: [
        { find: '@', replacement: resolve(__dirname, '/src') }
      ]
    },

    //css 预处理器配置
    module: {//这个节点，用于配置所有第三方模块加载器
      rules: [//所有第三方模块的匹配规则
        //配置处理.scss文件的第三方loader规则
        { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] },
      ]
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/element/index.scss" as *;
                           @use "@/styles/index.scss" as *;
                           @use "@/styles/theme.scss" as *;
                           @use "@/styles/mixin/index.scss" as *;
                           @use "@/styles/islands/index.scss" as *;`
        },

      }
    },
    // 环境/代理配置
    server: {
      host: env.VITE_HOST,
      port: Number(env.VITE_PORT),
      open: true,
      proxy: {
        '/api': {
          target: env.AGENT_HOST,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
          // pathRewrite: {
          //   '^/api': ''
          // }
        },
      },
    }
  }
});